package com.alibaba.sample.kantiezi.dal.dao.ibatis;

import com.alibaba.sample.kantiezi.dal.dao.SequenceDao;
import com.alibaba.sample.kantiezi.dal.dataobject.Sequence;

import com.ibatis.dao.client.DaoException;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class IbatisSequenceDao extends SqlMapClientDaoSupport
        implements SequenceDao {
    /**
     * This is a generic sequence ID generator that is based on a database table called 'SEQUENCE',
     * which contains two columns (NAME, NEXTID).  This approach should work with any database.
     *
     * @param name The name of the sequence.
     *
     * @return The Next ID
     */
    public synchronized int getNextId(String name) {
        Sequence sequence = new Sequence(name, -1);

        sequence = (Sequence) getSqlMapClientTemplate().queryForObject("getSequence", sequence);

        if (sequence == null) {
            throw new DaoException("Error: A null sequence was returned from the database (could not get next "
                                   + name + " sequence).");
        }

        Object parameterObject = new Sequence(name, sequence.getNextId() + 1);

        getSqlMapClientTemplate().update("updateSequence", parameterObject);

        return sequence.getNextId();
    }
}
